import datetime
import hashlib
import re

import pymongo
from bson import ObjectId

from database import HOST
from database.redis_con import redis_con

uri = "mongodb://centros:panchengliang9730012Cem@120.48.11.191:61447/admin"
client = pymongo.MongoClient(uri)
db = client['Movies']
movieCol = db['movie']
categorCol = db['category']
videoCol = db['video']


def save_categories(cate):
    if not categorCol.find_one({'url': cate['url']}):
        categorCol.insert_one(cate)


def get_categories():
    result = []
    cursor = categorCol.find({})
    for c in cursor:
        result.append(dict(c))
    return result


def get_category(cate):
    return categorCol.find_one({'category': cate})


def get_movie(title='', url='', md5='', name='', id=''):
    if name:
        query = {'name': name}
    if title:
        query = {'title': title}
    if url:
        query = {'url': url}
    if md5:
        query = {'md5': md5}
    if id:
        query = {'_id': ObjectId(id)}
    if not md5 and not title and not url and not id:
        return
    return movieCol.find_one(query)


def gen_movie_md5(url):
    match = re.search(r'https?://.*?\.com/(.*)', url)

    if match:
        text = match.group(1)  # 输出: dy/2025-08-20/47660.html
        return hashlib.md5(text.encode('utf-8')).hexdigest()


def save_movie(m):
    try:
        now = datetime.datetime.now()
        nowStr = now.strftime('%Y-%m-%d %H:%M:%S')
        md5 = m['md5']
        m.update({
            'updatedAt': nowStr,
        })
        if movie := movieCol.find_one({'$and': [{'title': m['title']}, {'md5': md5}]}):
            print(nowStr, '旧电影', movie['title'], movie['_id'])
            return 0
        elif movie := movieCol.find_one({'$and': [{'title': {'$ne': m['title']}}, {'md5': md5}]}):
            movieCol.update_one({'md5': md5}, {'$set': m})
            print(nowStr, '更新电影', movie['title'], movie['_id'])
            return 1
        else:
            movieCol.insert_one(m)
            print(nowStr, '新电影', m)
            return 1

    except:
        return save_movie(m)


def save_tv(tv):
    try:
        now = datetime.datetime.now()
        nowStr = now.strftime('%Y-%m-%d %H:%M:%S')
        md5 = hashlib.md5(tv['url'].encode('utf-8')).hexdigest()
        update_key = hashlib.md5(tv['title'].encode('utf-8')).hexdigest()
        tv.update({
            'title': tv['title'],
            'md5': md5,
            'updatedAt': nowStr,
        })
        if redis_con.sadd('movie_md5', md5) and redis_con.sadd('update', update_key):
            tv.update({'createdAt': nowStr})
            movieCol.insert_one(tv)
            print('新剧集', tv)
            return 1
        else:
            movieCol.update_one({'md5': md5}, {'$set': tv})
            print('更新剧集', tv)
            return 1

    except:
        return save_movie(tv)


def get_movie_by_name(name, fuzzy=True):
    if fuzzy:
        return movieCol.find_one({'name': {'$regex': name}})
    return movieCol.find_one({'name': name})


def save_tv_list(tvs):
    total = len(tvs)
    save_count = 0
    for m in tvs:
        save_count += save_tv(m)
    return total > save_count


def save_movie_list(movies):
    total = len(movies)
    save_count = 0
    for m in movies:
        save_count += save_movie(m)
    return total > save_count


def get_undetail_movie(debug):
    try:
        exclude_keywords = ["真人秀", "纪录片", "记录片", "演唱会", "综艺"]
        # 构建正则排除条件
        regex_pattern = "|".join(exclude_keywords)  # 真人秀|纪录片|记录片|演唱会|综艺
        query = {
            'updated': 1,
            'title': {'$not': {'$regex': regex_pattern}}
        }
        if debug:
            query.update({'main_category': 'movie'})
        return movieCol.find_one_and_update(
            query,
            {'$set': {'updated': -1}},
            sort=[('isRecommend', pymongo.DESCENDING), ('date', pymongo.DESCENDING)]
        )
    except Exception as e:
        print(f"Error in get_undetail_movie: {e}")
        return None


def get_failed_movie():
    ret = movieCol.find_one(
        {'detailed': -1}
    )
    return ret


def delete_movie(m):
    movieCol.delete_one(m)


def del_same_name_movie(m):
    title = m['title']
    name = m['name']
    url = m['url']
    count = movieCol.count_documents({'title': title, 'name': name})
    if count == 1:
        return
    cursor = movieCol.find({'title': title, 'name': name}).sort(
        [('valid', pymongo.DESCENDING), ('updatedAt', pymongo.DESCENDING)])
    index = 0
    for next in cursor:
        if index > 0:
            print('删除重复条目', title, url)
            movieCol.delete_one(next)
        index += 1
    count = movieCol.count_documents({'url': url})
    if count == 1:
        return
    cursor = movieCol.find({'url': url}).sort(
        [('valid', pymongo.DESCENDING), ('updatedAt', pymongo.DESCENDING)])
    index = 0
    for next in cursor:
        if index > 0:
            print('删除重复条目', title, url)
            movieCol.delete_one(next)
        index += 1


def save_movie_detail(m):
    m.update({
        'updatedAt': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    })
    movieCol.update_one({'_id': m['_id']}, {'$set': m})


def clear_detail():
    movieCol.update_many({}, {'$set': {'detailed': 0}})


def get_invalid_movie():
    return movieCol.find_one({'$and': [
        {'valid': {'$exists': False}},
        {'online': {'$ne': []}}
    ]}, {'md5': 1, 'name': 1, 'online': 1, 'title': 1}, sort=[('date', pymongo.DESCENDING)])


def set_movie_online_verified(movie, verified, valid):
    movieCol.update_one({'md5': movie['md5']}, {'$set': {'online': verified, 'valid': valid}})


def get_movie_for_update_category():
    return movieCol.find_one({'$and':
                                  [{'main_category': {'$exists': False}},
                                   {'category': {'$exists': True}}]
                              }, {'category': 1, 'md5': 1, 'title': 1})


def get_movie_by_url(url):
    return movieCol.find_one({'url': url})


def update_movie_category(movie):
    movieCol.update_one({'md5': movie['md5']}, {'$set': movie})
    print(movie['title'], movie['main_category'], movie['sub_category'])


def get_uncate_movie():
    cursor = movieCol.find({'category': {'$exists': False}}, {'md5': 1, 'title': 1, 'valid': 1})
    ret = []
    for c in cursor:
        ret.append(c)
    return ret


def find_my_category(movie):
    return movieCol.find_one({'md5': movie['md5'], 'category': {'$exists': True}}, {'category': 1})


def save_video_online(online):
    md5 = online['md5']
    if redis_con.sadd('video_link', md5) or not movieCol.find_one({'video_link': 'video_link'}):
        videoCol.insert_one(online)


def reset_detail():
    movieCol.update_many({'updated': {'$ne': 1}}, {'$set': {'updated': 1}})
